package com.jzy.message.util.common;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;

import com.jzy.message.activities.base.AppRequestInterface;
import com.jzy.message.util.json.JsonUtil;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.regex.Pattern;

public class CommUtility {
	public static void ChangeImageviewBitmap(final ImageView imageview, Bitmap bitmap) {
		imageview.setImageBitmap(bitmap);

		new Thread(new Runnable() {
			@Override
			public void run() {
				imageview.invalidate();
			}
		});
	}

	public static List<PackageInfo> getAllApps(Context context) {
		PackageManager pManager = context.getPackageManager();
		// 获取手机内所有应用

		return pManager.getInstalledPackages(0);
	}

	public static boolean startApp(Context context, String strAppName) {

		PackageManager pManager = context.getPackageManager();
		List<PackageInfo> apps = getAllApps(context);
		// 获取手机内所有应用
		for (int i = 0; i < apps.size(); i++) {
			PackageInfo pak = (PackageInfo) apps.get(i);
			// 判断是否为目标应用程序
			if (pManager.getApplicationLabel(pak.applicationInfo).toString()
					.equals(strAppName)) {

				Intent intent = new Intent();
				intent = pManager.getLaunchIntentForPackage(pak.applicationInfo.packageName);

				if(intent != null)
				{
					context.startActivity(intent);
					return true;
				}

				return false;
			}
		}

		return false;
	}

	private boolean openApp(Context context, String packageName) {
		PackageManager pManager = context.getPackageManager();
		PackageInfo pi = null;
		try {
			pi = pManager.getPackageInfo(packageName, 0);
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
		if(pi == null)
			return false;

		Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
		resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER);
		resolveIntent.setPackage(pi.packageName);
		List<ResolveInfo> apps = pManager.queryIntentActivities(resolveIntent, 0);
		ResolveInfo ri = apps.iterator().next();
		if (ri != null) {
			String className = ri.activityInfo.name;
			Intent intent = new Intent(Intent.ACTION_MAIN);
			intent.addCategory(Intent.CATEGORY_LAUNCHER);
			ComponentName cn = new ComponentName(packageName, className);
			intent.setComponent(cn);
			context.startActivity(intent);
			return true;
		}
		return false;
	}
	/*public static String[] getmondayTosunday() {
		// TODO Auto-generated method stub
		String[] result=new String[7];
		Calendar c = Calendar.getInstance();
		int weekday = c.get(7)-1;
		c.add(5,-weekday);
		//c.add(5, 1);
		//result[0]=c.getTime().toString();
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
		for(int i=0;i<7;i++)
		{
			c.add(5,1);
			result[i]=sdf.format(c.getTime()).toString();
		}
		return result;
	}*/
	//当前时间是星期几
	public static String getWeekOfDate() {
		String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
		Calendar cal = Calendar.getInstance();
		Date curDate = new Date(System.currentTimeMillis());
		cal.setTime(curDate);
		int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
		if (w < 0)
			w = 0;
		return weekDays[w];
	}
	public static int getVerCode(Context context,String PackageName) {
		int verCode = -1;
		try {
			verCode = context.getPackageManager().getPackageInfo(
					PackageName, 0).versionCode;
		} catch (NameNotFoundException e) {

		}
		return verCode;
	}

	public static String getVerName(Context context,String PackageName) {
		String verName = "";
		try {
			verName = context.getPackageManager().getPackageInfo(
					PackageName, 0).versionName;
		} catch (NameNotFoundException e) {
			return "";
		}
		return verName;
	}
	public static void showmsg(Context contex,String msg)
	{
		Toast.makeText(contex, msg, Toast.LENGTH_LONG).show();
	}
	//json时间转换
	public static String ConvertJsonDateToCommonDate(String jsonDate)
	{
		try {
			String resultString=jsonDate.substring(6, jsonDate.length()-2);
			Date date = new Date(Long.parseLong(resultString));
			DateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			return format2.format(date);
			//date.toLocaleString("yyyy-MM-dd HH:mm:ss");
		}
		catch (Exception e)
		{
			return "";
		}
	}
	//html转text
	public static String Html2Text(String inputString) {
		String htmlStr = inputString; //含html标签的字符串
		String textStr ="";
		java.util.regex.Pattern p_script;
		java.util.regex.Matcher m_script;
		java.util.regex.Pattern p_style;
		java.util.regex.Matcher m_style;
		java.util.regex.Pattern p_html;
		java.util.regex.Matcher m_html;

		try {
			String regEx_script = "<[//s]*?script[^>]*?>[//s//S]*?<[//s]*?///[//s]*?script[//s]*?>"; //定义script的正则表达式{或<script[^>]*?>[//s//S]*?<///script> }
			String regEx_style = "<[//s]*?style[^>]*?>[//s//S]*?<[//s]*?///[//s]*?style[//s]*?>"; //定义style的正则表达式{或<style[^>]*?>[//s//S]*?<///style> }
			String regEx_html = "<[^>]+>"; //定义HTML标签的正则表达式

			p_script = Pattern.compile(regEx_script,Pattern.CASE_INSENSITIVE);
			m_script = p_script.matcher(htmlStr);
			htmlStr = m_script.replaceAll(""); //过滤script标签

			p_style = Pattern.compile(regEx_style,Pattern.CASE_INSENSITIVE);
			m_style = p_style.matcher(htmlStr);
			htmlStr = m_style.replaceAll(""); //过滤style标签

			p_html = Pattern.compile(regEx_html,Pattern.CASE_INSENSITIVE);
			m_html = p_html.matcher(htmlStr);
			htmlStr = m_html.replaceAll(""); //过滤html标签
			//替换一些特殊的字符
			htmlStr=htmlStr.replace("&ldquo;", "“");
			htmlStr=htmlStr.replace("&hellip;", "…");
			htmlStr=htmlStr.replace("&mdash;", "-");
			htmlStr=htmlStr.replace("&nbsp;", " ");
			htmlStr=htmlStr.replace("&rdquo;", "”");
			htmlStr=htmlStr.replace("&le;", "<=");
			htmlStr=htmlStr.replace("&ge;", ">=");
			htmlStr=htmlStr.replace("\n", "");
			htmlStr=htmlStr.replace("\r", "");
			htmlStr=htmlStr.replace("&middot;", "·");
			//去掉所有空格
			htmlStr=htmlStr.replaceAll("\\s*", "");
			textStr = htmlStr;

		}catch(Exception e) {
			System.err.println("Html2Text: " + e.getMessage());
		}

		return textStr;//返回文本字符串
	}
	//获取手机ip
	public static String getLocalIpAddress3() {
		try {
			for (Enumeration<NetworkInterface> en = NetworkInterface
					.getNetworkInterfaces(); en.hasMoreElements();) {
				NetworkInterface intf = en.nextElement();
				for (Enumeration<InetAddress> enumIpAddr = intf
						.getInetAddresses(); enumIpAddr.hasMoreElements();) {
					InetAddress inetAddress = enumIpAddr.nextElement();
					if (!inetAddress.isLoopbackAddress()) {
						return inetAddress.getHostAddress().toString();
					}
				}
			}
		} catch (SocketException ex) {
			Log.e("IpAddress", ex.toString());
		}
		return null;
	}
	//将实体类型的数组转换成实体类型的集合
	public static <T> void fromArrayToCollection(T[] a,Collection<T> c){
		for (T t : a) {
			c.add(t);
		}
	}
	//判断接收到的json数据是否正确
	public static boolean IsResponseCorrect(String jsonstr)
	{
		try
		{
			String Code= JsonUtil.getCodeOfResponse(jsonstr);
			if(Code.equals(""))
				Code=JsonUtil.getCodeOfResponse1(jsonstr);
			if(Code.equals(AppRequestInterface.Sucess)||Code.equals(AppRequestInterface.Sucess0))
			{
				return true;
			}
			return false;
		}
		catch (Exception e)
		{
			return  false;
		}
	}
}
